/*
 * orange v1.0.0
 * Copyright 2016 XiaoXiong
 */
(function() {
	'use strict';
	
	define('orange', ['jquery'], function($) {
		var _appConfig = {	//	应用默认配置
			ajaxLoadFlag: '',
			getAppContextServiceUrl: 'pms/getAppContext.service',
			loginUrl: 'login',
			logoutUrl: 'logout',
			indexUrl: 'main/index'
		},  _appContext = {	//	应用上下文，包含组织、用户、应用、资源、角色、参数、字典
			organization: null,
			user: null,
			application: null,
			resource: null,
			role:null,
			/*parameter: null,*/
			parameter: {
				aid:[{}],
				paramType:[]
			},
			dictionary: null
		}, _appLogger = {
			level: 'INFO'
		}, _pageContext = [];	//	页面上下文，绑定交互参数到页面选择器
		
		//	绑定应用上下文
		//	getAppContextServiceUrl(String): 获取应用上下文远程服务地址
		function _bindAppContext(getAppContextServiceUrl) {
			var promise = $.ajax({
				type: 'post',
				dataType: 'json',
				url: getAppContextServiceUrl,
				success: function(data) {
					var result = data.data || null;
					if(result != null && data.success) {
						_appContext.organization = {
								oid: result.oid, 
								oname: result.oname?result.oname:"", 
								ocode: result.ocode?result.ocode:"" };
						_appContext.user = {id: result.id, username: result.username};
						_appContext.application = null;
						_appContext.resource = result.resourceEntitys;
						_appContext.role = result.roleEntitys;
						_appContext.parameter = result.paramEntitys;
						_appContext.dictionary = result.dictEntitys;
					}
				}
			});
			return promise;
		}
		
		//	获取应用上下文
		//	type(String): ORGANIZATION、USER、APPLICATION、RESOURCE、ROLE、PARAMETER、DICTIONARY
		function getAppContext(type) {
			if(typeof type === 'string') {
				type = type.toUpperCase();
				switch(type) {
					case 'ORGANIZATION':
						return _appContext.organization;
					case 'USER':
						return _appContext.user;
					case 'APPLICATION':
						return _appContext.application;
					case 'RESOURCE':
						return _appContext.resource;
					case 'ROLE':
						return _appContext.role;
					case 'PARAMETER':
						return _appContext.parameter;
					case 'DICTIONARY':
						return _appContext.dictionary;
					default:
						return _appContext;
				}
			} else {
				return _appContext;
			}
		}
		
		//	清空应用上下文
		function clearAppContext() {
			for(var i in _appContext) {
				_appContext[i] = undefined;
			}
		}
		
		//	创建页面上下文
		//	pageSelector(String): 页面选择器,param(Object): 页面参数
		function createPageContext(pageSelector, param) {
			var dom = $('#' + pageSelector);
			if(dom) {
				_pageContext.push({page: dom, key: pageSelector});
				dom.data(pageSelector, param);
			}
		}
		
		//	获取页面上下文
		//	pageSelector(String): 页面选择器
		function getPageContext(pageSelector) {
			var dom = $('#' + pageSelector);
			if(dom) {
				return dom.data(pageSelector);
			}
		}
		
		//	清空页面上下文
		function clearPageContext() {
			for(var i=0; i<_pageContext.length; i++) {
				var dom = _pageContext[i].dom, key = _pageContext[i].key;
				dom.removeData(key);
			}
		}
		
		//	设置日志等级
		//	level(String): 日志等级
		function _setLoggerLevel(level) {
			if(typeof level === 'string') {
				level = level.toUpperCase();
				switch(level) {
					case 'INFO':
						_appLogger.level = 'INFO';
						break;
					case 'DEBUG':
						_appLogger.level = 'DEBUG';
						break;
					case 'ERROR':
						_appLogger.level = 'ERROR';
						break;
					default:
						break;
				}
			}
		}
		
		//	启动应用
		function start() {
			_bindAppContext(_appConfig.getAppContextServiceUrl).then(_renderIndex());
		}
		
		//	重启应用
		function restart() {
			stop();
			start();
		}
		
		//	停止应用
		function stop() {
			sessionStorage.clear();	//	清空会话缓存
			clearAppContext();	//	重置应用上下文
			clearPageContext();	//	重置页面上下文
			$.post(_appConfig.appLogoutUrl, function(data) {
            	if(data == 'success') {
            		location.href = _appConfig.appLoginUrl;
            	}
            });
		}
		
		/*function stop() {  // 停止应用--退出登录
			sessionStorage.clear();
			$.post(appConfigs.appLogoutUrl, function(data) {
            	if(data == 'success') {
            		location.href = appConfigs.appLoginUrl;
            	}
            });
		}*/
		
		//	渲染应用首页
		function _renderIndex() {
			$('#main_logger').append('<p><h3> >> 应用上下文加载完毕，开始渲染首页 ...</h3></p>');
			setTimeout(function() {
				require([_appConfig.indexUrl]);
			}, '500');
		}
		
		//	加载样式文件
		//	href(String): 样式文件远程地址
		function _loadCss(href) {
			var aLinks = $('head link'), i=0, len = aLinks.length;
			for(i=0; i<len; i++) {
				if(aLinks[i].href == href) {
					return;
				}
			}
			$('<link>').attr({ rel: 'stylesheet', type: 'text/css', href: href }).appendTo('HEAD');
		}
		
		//	加载脚本文件
		//	url(String): 脚本文件远程地址
		function _loadScript(url) {
			$.getScript(url);
		}
		
		//	加载远程内容到指定页面
		//	params(Object): {url(String): 远程加载地址, target(String): 被加载元素的ID, selector(String): 页面选择器, 
		//	replace(true/false): 是否替换原有内容, success(Function): 加载成功回调函数}
		function loadPage(params) {
			if(params && typeof params === 'object') {
				var url = params['url'], target = params['target']?$('#'+ params['target']) : $('BODY'), selector = params['selector'], 
						data = params['data'], type = data?'POST' : 'GET', replace = params['replace'] === false?false : true, callback = undefined;
				callback = (params['success'] && typeof params['success'] === 'function')?callback = params['success'] : callback;
				if(typeof url !== 'string' || !url) {
					throw new Error('加载远程内容到指定页面失败，地址参数非法');
				} else {
					if(replace) {
						target.empty();
					}
					$.ajax({
						url: url,
						type: type,
						data: data,
						dataType: 'html'
					}).done(function(responseText) {
						var response = $.parseHTML(responseText, true), scripts = [];
						target.append(selector?$('<div>').append(response).find(selector):responseText);
						for(var i=0; i<response.length; i++) {
							if(response[i].nodeName == "LINK") {
								_loadCss(response[i].href);
							}else if(response[i].nodeName == "SCRIPT") {
								scripts.push(response[i].src);
							}
						}
						for(var i=0; i<scripts.length; i++) {
							_loadScript(scripts[i]);
						}
					}).always(callback && function(responseText) {
						callback.call(callback, responseText);
					});
				}
			} else {
				throw new Error('加载远程内容到指定页面失败，参数非法');
			}
		}
		
		//所要判段的字符串为空
		function strIsBlank(str) {
			if(str != "" && str != null && str != "undefined") {
				return false;
			} else {
				return true;
			}
		}
		
		//	全局异步请求发送处理
		$(document).ajaxSend(function(event, xhr, settings) {
			if(settings.url && settings.url.indexOf('?') != -1) {
				settings.url = settings.url.replace('?', '?' + Math.random() + '&');
			} else {
				settings.url += '?' + Math.random(); 
			}
		});
		
		return window.orange = {
			getAppContext: getAppContext,
			createPageContext: createPageContext,
			getPageContext: getPageContext,
			restart: restart,
			start: start,
			stop: stop,
			loadPage: loadPage,
			strIsBlank: strIsBlank
		};
	});
})();
